package com.kongt.controllers;
 
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.kongt.domain.Kv;
import com.kongt.domain.KvRepository; 
import com.kongt.model.KvPageable;
import com.kongt.model.KvSearchModel;
import com.kongt.model.PageModel;
import com.kongt.utils.PageUtil;

/**控制器
 * @author kongt 2017年10月23日
 *
 */
@Controller
@RequestMapping({"/home","/"}) 
public class HomeController {
 
    //kv jpa
    @Autowired
    private KvRepository kvRepository;
	
	 
	@RequestMapping({"/","/index"})
	public String index(Model m,HttpServletRequest request,KvSearchModel search) {
		PageModel<Kv> pmodel = new PageModel<Kv>(); 
		search.setAsc(false);
		search.setSortFiled("id"); 
		//匹配所有字段
		ExampleMatcher matcher = ExampleMatcher.matchingAny()
				//忽略id字段
				.withIgnorePaths("id")
				 //字符类匹配类型为包含 
				.withStringMatcher(StringMatcher.CONTAINING);
		Example<Kv> example = Example.of(new Kv(null, search.getKeyword(), search.getKeyword()), matcher);  
		Page<Kv> pageKv = kvRepository.findAll(example, new KvPageable<KvSearchModel>(search));   
		pmodel.setCount(pageKv.getTotalElements());  
		pmodel.setRows(pageKv.getContent());  
		PageUtil pageUtil = new PageUtil(request,search.getPageIndex(), search.getPageSize(),(int)pageKv.getTotalElements());  
		m.addAttribute("search",search);  
		m.addAttribute("pmodel", pmodel); 
		m.addAttribute("pageUtil", pageUtil);
		return "home/index";
	}

	
	@RequestMapping({"/api"})
	public String api() { 
		return "home/api";
	}
}
